package com.xhblog.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xhblog.entity.SysUser;
import com.xhblog.entity.dto.LoginDto;
import com.xhblog.enums.ErrorCode;
import com.xhblog.result.Result;
import com.xhblog.service.LoginService;
import com.xhblog.service.SysUserService;
import com.xhblog.utils.JwtUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author pengyouhong
 * create 2022/5/18 18:26
 */

@Service
@Log4j2
public class LoginServiceImpl implements LoginService {


    private static final String slat = "loveYou3000times";
    @Resource
    private SysUserService sysUserService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public Result login(LoginDto loginDto) {
        /*
         * 1.检验参数是否合法
         * 2.根据用户名，密码，从数据库查询，不存在，登录失败，存在则登录成功，使用jwt,返回token给前端
         * 3.token放到redis中，设置过期时间
         * 登录验证时，先认证token字符串是否合法，去验证redis是否存在
         * */

        String account = loginDto.getAccount();
        String password = loginDto.getPassword();

        //验证参数是否合法
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }

        password = DigestUtils.md5DigestAsHex((password + slat).getBytes());

        SysUser sysUser = sysUserService.findUser(account, password);

        if (sysUser == null) {
            log.error("用户名或密码不存在");
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }

        String token = JwtUtils.createToken(sysUser.getId());

        //token放到redis中，设置过期时间
        redisTemplate.opsForValue().set("TOKEN" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);

        return Result.success(token);

    }

}
